const app=getApp();
const globalData=app.globalData;
const apiUrl = globalData.wxApi;

export function getStoreData(k){
  try{
   return wx.getStorageSync(k)
  }catch(e){
    return ''
  }
}

export function setStoreData(key, data){
  wx.setStorage({
    key,
    data,
    success:function(res){
      // 
    }
  })
}

export function httpPost(url,postData,load={}){
  const _wx = wx
  let title = '加载中...'
  let flag = false
  if(!Object.keys(load).length){
    load = {
      isLoad:false,
      title
    }
  }
  if(load&&load.isLoad&&load.title){
    wx.showLoading({
      title: load.title
    })
    flag = true
  }
  
  return new Promise((resolve,reject)=>{
    wx.request({
      url: apiUrl+url,
      data: postData,
      method:"POST",
      header:{
        "content-type":"application/json",
        "Authorization":getStoreData("token")||''
      },
      success:res=>{
        if(flag){
          _wx.hideLoading()
        }
        const result = res.data
        // console.log('result',result)
			if (result&&result.code == '1001001020') {
				_wx.showToast({
          title:result.message||'token失效',
          icon:'none',//默认success
          duration:1500
        })
        setTimeout(()=>{
          _wx.clearStorage()
          _wx.redirectTo({
            url:'/pages/index/index'
          })
        },1500)
			}else if(result&&result.code == 0){
        resolve(result)
      } else{
        _wx.showToast({
          title:result.message||'请求异常',
          icon:'none',//默认success
          duration:1500
        })
        reject(res)
      }
      },
      fail:function(res){
        
        if(load&&load.isLoad&&load.title){
          _wx.hideLoading()
        }
        _wx.showToast({
          title:result.message||'请求异常',
          icon:'none',//默认success
          duration:1500
        })
        reject(res)
      }
    })
  })
}

export function httpGet(url,load={}){
  const _wx = wx
  let title = '加载中...'
  let flag = false
  if(!Object.keys(load).length){
    load = {
      isLoad:false,
      title
    }
  }
  if(load&&load.isLoad&&load.title){
    wx.showLoading({
      title: load.title
    })
    flag = true
  }
  return new Promise((resolve,reject)=>{
    wx.request({
      url:apiUrl+url,
      method:"GET",
      header:{
        "content-type":"application/json;charset=UTF-8",
        "Authorization":getStoreData("token")||''
      },
      success:res=>{
        if(flag){
          _wx.hideLoading()
        }
        let result = res.data
			if (result&&result.code == '1001001020') {
				_wx.showToast({
          title:result.message||'token失效',
          icon:'none',//默认success
          duration:1500
        })
        setTimeout(()=>{
          _wx.clearStorage()
          _wx.redirectTo({
            url:'/pages/index/index'
          })
        },1500)
			}else if(result&&result.code =='0'){
        resolve(result)
      } else{
        if(url.indexOf('/todayIncomeByLeading')===-1&&url.indexOf('/todayIncome')===-1){
          _wx.showToast({
            title:result.message||'请求异常',
            icon:'none',//默认success
            duration:1500
          })
        }
        reject(res)
       }
      },
      fail:function(res){
        if(flag){
          _wx.hideLoading()
        }
        _wx.showToast({
          title:result.message||'请求异常',
          icon:'none',//默认success
          duration:1500
        })
        reject(res)
      }
    })
  })
}

export function dealNum(v,value1){
  const value = String(value1||'')
  if(v==='phone'&&value.length>7){
    return value.replace(/(\d{3})\d*(\d{4})/, "$1****$2"); 
  }else if(v==='card'&&value.length>8){
     return value.slice(0, 4) + " **** **** " + value.slice(value.length - 4)
  }else if(v==='name'){
    if(value.length==2){
      return value.substring(0,1)+'*' //截取name 字符串截取第一个字符，
    }else if(value.length==3){
      return "**"+value.substring(2,3)//截取第一个和第三个字符
    }else if(value.length>3){
      return value.substring(0,1)+"**"+value.substring(3,value.length)//截取第一个和大于第4个字符
    } else{
      return ""
    }
  }else{
    return ''
  }
}
 
// 如果有时间戳传来。则返回上一天日期，否则返回今天年-月-日时间
export function lastDayFun(v,k,j) { 
  let date2 = new Date().getTime();
  if (v) {
    date2 = Number(new Date(String(v).replace(/-/g, '/')).getTime()) - (1000 * 60 * 60 * 24);
  }else if(k){
    date2 = new Date(k).getTime()
  }else if(j){
    date2 = new Date(j).getTime()
  }
  const date = new Date(date2);
  const year = date.getFullYear();
  const month =
    Number(date.getMonth()) > 8
      ? Number(date.getMonth()) + 1
      : "0" + (Number(date.getMonth()) + 1);
  const date1 = Number(date.getDate()) > 9 ? date.getDate() : "0" + date.getDate();

  if(k){
    const days=new Date(year,Number(date.getMonth()) + 1,0).getDate()
    //如果是月份，返回该选择月份的  年-月-日（最后一日）
    return String(year) + "-" + String(month) + "-" + String(days);
  }else{
    //如果是日期，返回该选择日期的  年-月-日
    return String(year) + "-" + String(month) + "-" + String(date1);
  }
  
}

export function weekDay(v){
  let now=""
  if(v){
    now = new Date(v);
  }else{
    now = new Date();
  }
  let nowTime = Number(now.getTime());
  let day1 = Number(now.getDay());//当前星期几，如果是0则表明是星期日
  let oneDayTime = 24*60*60*1000;
  //显示周一
  const day = day1 > 0 ? day1 : 7
  let MondayTime = nowTime - (day-1)*oneDayTime;
  //显示周日
  let SundayTime = nowTime + (7-day)*oneDayTime;
  //初始化日期时间
  let monday = new Date(MondayTime);
  let sunday = new Date(SundayTime);
  
  const month1 =
  Number(monday.getMonth()) > 8
      ? Number(monday.getMonth()) + 1
      : "0" + (Number(monday.getMonth()) + 1)
 const month2 =
  Number(sunday.getMonth()) > 8
          ? Number(sunday.getMonth()) + 1
          : "0" + (Number(sunday.getMonth())+ 1);
  const date1 = Number(monday.getDate()) > 9 ? monday.getDate() : "0" + monday.getDate();
  const date2 = Number(sunday.getDate()) > 9 ? sunday.getDate() : "0" + sunday.getDate();
  const year1 = monday.getFullYear();
  const year2 = sunday.getFullYear();
  return [String(year1) + "-" + String(month1) + "-" + String(date1),String(year2) + "-" +String(month2) + "-" + String(date2)];
}

export function formatDistance(v,type){
 if(v&&v<1000){
    return v+(type?'m':'米')
  }else if(v&&v>=1000){
    return (v/1000).toFixed(2)+(type?'km':'公里')
  }else{
    return '--'
  }
}
export function formatStr(v,num){
  if(v&&String(v).length>num){
     return String(v).substring(0,num)+'...'
   }if(v&&String(v).length<=num){
    return String(v)
  } else{
     return '--'
   }
 }

 /**
 * 百度地图经纬度转为腾讯地图经纬度
 * @param {Number} lat
 * @param {Number} lng
 * @returns
 */
export function bdMapToTxMap(lng, lat) {
  if (lng == '' && lat == '') {
		return {
			lng: '',
			lat: ''
		}
	}
	var x_pi = 3.14159265358979324 * 3000.0 / 180.0
	var x = lng - 0.0065
	var y = lat - 0.006
	var z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi)
	var theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi)
	var qqlng = z * Math.cos(theta)
	var qqlat = z * Math.sin(theta) 
  return { longitude:qqlng, latitude: qqlat};
}
 
/**
 * 腾讯地图转百度地图经纬度
 * @param {Number} lat
 * @param {Number} lng
 * @returns
 */
 export function txMapToBdMap(lng, lat) {
  if (lng == null || lng == '' || lat == null || lat == ''){
    return {
      lng: '',
      lat: ''
    }
  }
  var x_pi = 3.14159265358979324;
  var x = parseFloat(lng);
  var y = parseFloat(lat);
  var z = Math.sqrt(x * x + y * y) + 0.00002 * Math.sin(y * x_pi);
  var theta = Math.atan2(y, x) + 0.000003 * Math.cos(x * x_pi);
  var bmlng = (z * Math.cos(theta) + 0.0065).toFixed(5);
  var bmlat = (z * Math.sin(theta) + 0.006).toFixed(5); 

  return {
    longitude: bmlng,
    latitude: bmlat,
  };
} 